import 'package:cbec_app/components/base/base_image.dart';
import 'package:cbec_app/components/base/base_page.dart';
import 'package:cbec_app/components/base/text_nav_item.dart';
import 'package:cbec_app/components/common/common_style.dart';
import 'package:cbec_app/components/common/not_found.dart';
import 'package:cbec_app/components/common/sort_flitter_box.dart';
import 'package:cbec_app/components/base/base_nav_bar.dart';
import 'package:cbec_app/components/goods/goods_item.dart';
import 'package:cbec_app/pages/classify/controller/search_result_ctr.dart';
import 'package:cbec_app/routes/routes.dart';
import 'package:cbec_app/utils/ThemeConfig.dart';
import 'package:cbec_app/utils/logger.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../../goods/binding/goods_detail_binding.dart';
import '../../goods/view/goods_detail_page.dart';

///搜索结果页
class SearchResultPage extends GetView<SearchResultController> {
  const SearchResultPage({super.key});
  @override
  Widget build(BuildContext context) {
    return GetBuilder<SearchResultController>(
      builder: (controller) {
        return BasePage(
            navBgColor: Colors.white,
            iconType: IconType.back,
            isSearch: true,
            searchType: SearchStyleType.onlySearch,
            isDisable: false,
            placeholder: '输入关键字搜索',
            refreshController: controller.baseRefreshCtr,
            enablePullDown: true,
            enablePullUp: controller.isLoadData,
            onPageRefresh: controller.onPageRefresh,
            onPageLoading: controller.onPageLoading,
            textEditingController: controller.textEditingController,
            onInput: (value) {
              controller.startSearch(value);
            },
            children: [
              SortFlitterBox(
                showFlitter: true,
                curIndex: controller.filterIndex,
                sortList: controller.filterList,
                callback: (index) {
                  controller.dealFilterFiled(index);
                },
                showCallBack: (isGrid) {
                  controller.changeListStyle(isGrid);
                },
              ),
              Container(
                padding: EdgeInsets.only(left: 8.w, right: 8.w, top: 10.h, bottom: 20.h),
                child: controller.isGrid ? buildWrapWidget(controller) : buildListViewWidget(controller),
              )
            ]);
      },
    );
  }

  Widget buildListViewWidget(SearchResultController controller) {
    return Wrap(alignment: WrapAlignment.spaceBetween, runSpacing: 6.w, children: controller.goodsList.isNotEmpty ? controller.goodsList.map((item) => buildItemHWidget(item)).toList() : const [NotFound()]);
  }

  Widget buildItemHWidget(item) {
    return InkWell(
      onTap: () {
        final id = item['commodityId'];
        Get.to(
          () => GoodsDetailPage(flag: id), // 使用函数懒加载页面实例
          routeName: '${Routes.goodsDetail}?unique=${DateTime.now().millisecondsSinceEpoch}',
          arguments: {"id": id}, // 传递其它参数
          binding: GoodsDetailBinding(flag: id), // 将 tag 参数传递给绑定类
        );
      },
      child: Container(
        width: double.infinity,
        decoration: const BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(8)),
          color: Colors.white,
        ),
        child: Row(
          children: [
            Padding(
              padding: const EdgeInsets.all(10),
              child: ClipRRect(
                borderRadius: const BorderRadius.all(Radius.circular(8)),
                child: BaseImage(
                  url: item['mainImage'],
                  height: 100.w,
                  width: 100.w,
                ),
              ),
            ),
            Padding(
              padding: const EdgeInsets.symmetric(vertical: 30),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  goodsTypeTag(getGoodsTypeName(item['commodityType']), margin: const EdgeInsets.only(right: 5)),
                  Text(item['commodityName'], style: setTextStyle(12, FontWeight.w400, ThemeConfig.mainTextColor)),
                  Wrap(
                    runSpacing: 5.w,
                    children: [
                      for (var text in item?['discountLabel'])
                        BorderedText(
                          text: text,
                          padding: const EdgeInsets.only(left: 2, right: 2, top: 2, bottom: 2),
                          borderColor: ThemeConfig.themeColor,
                          textStyle: const TextStyle(fontSize: 11, color: ThemeConfig.themeColor),
                        ),
                    ],
                  ),
                  Row(
                    children: [
                      Text('¥', style: setTextStyle(12, FontWeight.w400, ThemeConfig.themeColor)),
                      const SizedBox(width: 2),
                      if (item['price'].toString().contains('.')) ...[
                        buildPriceRichText(item['price']),
                      ] else ...[
                        Text(item['price'].toString(), style: setTextStyle(15, FontWeight.w400, ThemeConfig.themeColor)),
                      ],
                    ],
                  )
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

  Wrap buildWrapWidget(SearchResultController controller) {
    return Wrap(
        alignment: WrapAlignment.spaceBetween,
        runSpacing: 6.w,
        children: controller.goodsList.isNotEmpty
            ? controller.goodsList
                .map((item) => GoodsItem(
                      goodsInfo: item,
                    ))
                .toList()
            : const [NotFound()]);
  }

  Widget buildPriceRichText(double price) {
    // 将价格转换为保留两位小数的字符串
    String priceStr = price.toStringAsFixed(2); // e.g., "123.45"
    List<String> parts = priceStr.split('.'); // 分离整数和小数部分

    return RichText(
      text: TextSpan(
        style: const TextStyle(color: ThemeConfig.themeColor), // 设置默认颜色
        children: [
          TextSpan(
            text: parts[0], // 整数部分
            style: const TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.bold,
            ),
          ),
          const TextSpan(
            text: '.', // 小数点
            style: TextStyle(
              fontSize: 12,
              fontWeight: FontWeight.w400,
            ),
          ),
          TextSpan(
            text: parts[1], // 小数部分
            style: const TextStyle(
              fontSize: 12,
              fontWeight: FontWeight.w400,
            ),
          ),
        ],
      ),
    );
  }
}
